CREATE procedure [dbo].[updateDep]
@bz integer = 1 --1为scm 0为bs
as
 set nocount on
 

	declare @dep_no_add varchar(100)
	declare @dep_no_parent varchar(100)
	declare @dep_name varchar(200)
	declare @dep_serial int

 ------------------------- 同步删除的部门
      delete from dt_dep where dep_no_add not in(select a.dep_no_add  from tmp_dt_dep a inner join dt_dep b on a.dep_no_add = b.dep_no_add) and dep_parent <> 0 and dep_no_add is not null

-------------------------部门更新
	update dt_dep set dep_name = b.dep_name,dep_no_parent = b.dep_no_parent from dt_dep a inner join tmp_dt_dep b on a.dep_no_add = b.dep_no_add



 ------------------------部门添加
	declare cur_tt cursor for 
	select dep_no_add,dep_no_parent,dep_name from tmp_dt_dep where dep_no_add not in(select a.dep_no_add from dt_dep a inner join tmp_dt_dep b on a.dep_no_add = b.dep_no_add) order by dep_no_add
	open cur_tt
	FETCH NEXT FROM cur_tt into @dep_no_add,@dep_no_parent,@dep_name
	while @@FETCH_STATUS = 0 
	begin
	    if @bz = 1
			select @dep_serial = module_dep+1 from wt_module where module_id = '0002'      --modify by zlibo 2013-05-18
		else
			select @dep_serial = reg_dep+1 from wt_reg 
		
		insert into dt_dep(dep_serial,dep_name,dep_no_add,dep_no_parent,dep_rule) values(@dep_serial,@dep_name,@dep_no_add,@dep_no_parent,0)
		
		if @bz = 1
			update wt_module set module_dep = module_dep + 1 where module_id = '0002'
		else
			update wt_reg set reg_dep = reg_dep + 1 
		FETCH NEXT FROM cur_tt into @dep_no_add,@dep_no_parent,@dep_name 
	end
	CLOSE cur_tt
	DEALLOCATE cur_tt  

--------------------------置dep_parent
	update dt_dep set dep_parent = isnull(b.dep_serial,10000) from dt_dep left join dt_dep b on dt_dep.dep_no_parent = b.dep_no_add 
	where dt_dep.dep_serial <> 10000 and ( isnull(dt_dep.dep_no_parent,'')<>'' or dt_dep.dep_no_parent is null )

---------------------------置dep_order和dep_no
 

        declare @level int   
        declare @count int

    	update dt_dep set dt_dep.dep_order=b.rn-1 from dt_dep a,
	(
		select t.*, rn=(select count(1) from dt_dep where 
		id<=t.id and dep_parent=t.dep_parent)
		from dt_dep t
	
	)b
	where a.dep_serial=b.dep_serial
	
  	select @level = max(level) from get_ChildDep(0)
    while @level > 0 
    begin        
		update dt_dep set dt_dep.dep_no=cast(b.dep_no as varchar)+right(cast(power(10,2) as varchar)+Convert(varchar,dbo.Sys_Convert(a.dep_order)),2)
		from dt_dep a,
		(
		select b.* from dt_dep a,dt_dep b where a.dep_parent=b.dep_serial
		)b
		where a.dep_parent=b.dep_serial

		set @level= @level -1 
    end
 

return